//
//  ReadWebController.m
//  FileSharing
//
//  Created by 祁俊喜 on 2024/4/23.
//

#import "ReadWebController.h"
#import <WebKit/WebKit.h>
#import "TXTDownloader.h"
#import "FileMacros.h"
#import "ZFNormalViewController.h"

@interface ReadWebController ()<WKUIDelegate,WKNavigationDelegate>

@property (nonatomic, strong) WKWebView *webView;

@property (nonatomic, strong) UIProgressView *progressView;

@end

@implementation ReadWebController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor systemGroupedBackgroundColor];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.view addSubview:self.webView];
        [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:(NSKeyValueObservingOptionNew) context:nil];
        [self.view addSubview:self.progressView];
    });
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemReply) target:self action:@selector(backItemAction)];
    
    UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemStop) target:self action:@selector(closeItemAction)];
    
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemFixedSpace) target:nil action:nil];
    spaceItem.width = 10;
    
    self.navigationItem.leftBarButtonItems = @[backItem,spaceItem,closeItem];
    
}

-(void)backItemAction {
    if (self.webView.canGoBack) {
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)closeItemAction {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        if (self.webView.estimatedProgress >= 1.0) {
            self.progressView.hidden = YES;
        }else{
            self.progressView.hidden = NO;
            self.progressView.progress = self.webView.estimatedProgress;
        }
    }
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    self.progressView.hidden = NO;
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    self.progressView.hidden = YES;
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSString *urlStr = navigationAction.request.URL.absoluteString;
    NSLog(@"当前地址：%@",urlStr);
    if ([urlStr hasSuffix:@"txt"]) {
        NSString *title = [[urlStr lastPathComponent] stringByRemovingPercentEncoding];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:@"检测到txt文件，确定要下载吗?" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *config = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            self.progressView.hidden = YES;
            TXTDownloader *down = [[TXTDownloader alloc] init];
            down.txtUrl = urlStr;
            down.progressHandler = ^(double progress) {
                NSString *total = [NSByteCountFormatter stringFromByteCount:progress countStyle:NSByteCountFormatterCountStyleFile];
                self.title = [NSString stringWithFormat:@"%@",total];
            };
            down.completionHandler = ^{
                self.title = [NSString stringWithFormat:@"下载完成"];
            };
            [down start];
        }];
        [alert addAction:cancel];
        [alert addAction:config];
        [self presentViewController:alert animated:YES completion:nil];
    }
    
    if ([urlStr hasSuffix:@"m3u8"] || [urlStr hasSuffix:@"mp4"]) {
        NSString *title = [[urlStr lastPathComponent] stringByRemovingPercentEncoding];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:@"检测到视频文件，确定要播放吗?" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *config = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            UIPasteboard *pb = [UIPasteboard generalPasteboard];
            pb.string = urlStr;
            ZFNormalViewController *vc = [[ZFNormalViewController alloc] init];
            vc.videoUrl = urlStr;
            [self.navigationController pushViewController:vc animated:YES];
        }];
        [alert addAction:cancel];
        [alert addAction:config];
        [self presentViewController:alert animated:YES completion:nil];
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}

-(WKWebView *)webView{
    if(!_webView){
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero];
        _webView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.allowsBackForwardNavigationGestures = YES;
        NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]];
        [_webView loadRequest:request];
    }
    return _webView;
}

- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, KNativeHeight, kScreenWidth, 1)];
        _progressView.trackTintColor = [UIColor clearColor];
        _progressView.progressTintColor = [UIColor systemBlueColor];
    }
    return _progressView;
}


@end
